#include "manager.h"
#include "ui_manager.h"

manager::manager(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::manager)
{
    ui->setupUi(this);
   //insert_database(3,"jason","192.168.2.1");
    //QTableView *tableView = new QTableView(this);
    //tableView->setMinimumSize(700, 500);
    QStandardItemModel *tableModel = new QStandardItemModel(this);
        ui->equipment_list->setModel(tableModel); // recommend to set model before detail settings

        // set columns
        QStringList columnTitles;
        columnTitles << "id" << "name" << "status" << "action";
        tableModel->setHorizontalHeaderLabels(columnTitles);
    //    tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); // column fit the contents

        // add contents
        for(int i = 0; i < 7; i++)
        {
            tableModel->setItem(i, 0, new QStandardItem(QString::number(i + 1)));
            tableModel->setItem(i, 1, new QStandardItem(QString("hello qt tablview %1").arg(i)));
            tableModel->setItem(i, 2, new QStandardItem("normal"));

            // add button to the last column
            QPushButton *button = new QPushButton("Start");

            // set custom property
            button->setProperty("id", i); // set custom property
            button->setProperty("name", QString("hello qt tablview %1").arg(i));
            button->setProperty("status", "normal");

            // set click event
            connect(button, SIGNAL(clicked()), this, SLOT(onTableBtnClicked()));

            // notice every time insert the button at the last line
            ui->equipment_list->setIndexWidget(tableModel->index(tableModel->rowCount() - 1, 3), button);
        }


    select_database();



}
//-----------------------插入数据
/*
    void manager::insert_database(int id,QString name,QString ip)
{

        QSqlDatabase db;

        // 连接SQLite数据库
        db = QSqlDatabase::addDatabase("QSQLITE","second");
        db.setDatabaseName("./test.db"); // 替换为你的数据库文件路径
        if (!db.open()) {
            qDebug() << "Failed to connect to database";
            //return;
        }else
            qDebug()<<"连接数据库成功"<<endl;

        QSqlQuery query(db);
      //------------------------
    query.exec("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name varchar(30), ip varchar(30))");
    query.prepare("INSERT INTO users (id,name, ip) VALUES (:id,:name, :ip)");
    query.bindValue(":name", name);
    query.bindValue(":ip", ip);
    if(!query.exec()) {
        qDebug() << "插入数据失败：" << query.lastError().text();
    }


    //-----------------------------------add button



   QSqlQueryModel *model = new QSqlQueryModel();
   // 设置要执行的 SQL 查询语句
   QString queryStr = "SELECT * FROM users"; // 假设数据库中有一个名为 "users" 的表
   // 执行查询
  // QSqlQuery query;
   if (query.exec(queryStr)) {
       model->setQuery(query);
   } else {
       qDebug() << "查询失败:" << query.lastError();
       //return -1;

   }
   int row = model->rowCount();
     qDebug() << "new equipment is num:" << row;

// add contents
   QSqlTableModel *tableModel = new QSqlTableModel(this);
      ui->equipment_list->setModel(tableModel); // recommend to set model before detail settings

   // add button to the last column
   QPushButton *button = new QPushButton("Start");

   button->setProperty("id", row); // set custom property设置按钮id为i
    button->setProperty("name", QString("hello qt tablview %1").arg(row));
   button->setProperty("status", "normal");

   // set click event
   connect(button, &QPushButton::clicked, this, &manager::onTableBtnClicked); // 使用新的连接语法

   // notice every time insert the button at the last line
  ui->equipment_list->setIndexWidget(tableModel->index(tableModel->rowCount() - 1, 3), button);




}
*/




 void manager::insert_database(int id,QString name,QString ip)
 {
     QStandardItemModel *tableModel = new QStandardItemModel(this);
         ui->equipment_list->setModel(tableModel); // recommend to set model before detail settings

         // set columns
         QStringList columnTitles;
         columnTitles << "id" << "name" << "status" << "action";
         tableModel->setHorizontalHeaderLabels(columnTitles);
     //    tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); // column fit the contents

         // add contents
         for(int i = 0; i < 7; i++)
         {
             tableModel->setItem(i, 0, new QStandardItem(QString::number(i + 1)));
             tableModel->setItem(i, 1, new QStandardItem(QString("hello qt tablview %1").arg(i)));
             tableModel->setItem(i, 2, new QStandardItem("normal"));

             // add button to the last column
             QPushButton *button = new QPushButton("Start");

             // set custom property
             button->setProperty("id", i); // set custom property
             button->setProperty("name", QString("hello qt tablview %1").arg(i));
             button->setProperty("status", "normal");

             // set click event
             connect(button, SIGNAL(clicked()), this, SLOT(onTableBtnClicked()));

             // notice every time insert the button at the last line
             ui->equipment_list->setIndexWidget(tableModel->index(tableModel->rowCount() - 1, 3), button);
         }

 }







void manager::select_database()
{


    QSqlDatabase db;

    // 连接SQLite数据库
    db = QSqlDatabase::addDatabase("QSQLITE","second");
    db.setDatabaseName("./test.db"); // 替换为你的数据库文件路径
    if (!db.open()) {
        qDebug() << "Failed to connect to database";
        //return;
    }else
        qDebug()<<"连接数据库成功"<<endl;
    QSqlQuery query(db);


   query.exec("SELECT * FROM users");//select为遍历


    while(query.next()) {
        int id = query.value(0).toInt();//value（0）表示低0列
        QString name = query.value(1).toString();
        QString ip = query.value(2).toString();
        qDebug() << "ID:" << id << " Name:" << name << " ip:" << ip;

        }

    // 创建查询模型
        QSqlQueryModel *model = new QSqlQueryModel();
        // 设置要执行的 SQL 查询语句
        QString queryStr = "SELECT * FROM users"; // 假设数据库中有一个名为 "users" 的表


        // 执行查询
       // QSqlQuery query;
        if (query.exec(queryStr)) {
            model->setQuery(query);
        } else {
            qDebug() << "查询失败:" << query.lastError();
            //return -1;

        }

        int rowCount = model->rowCount();
          qDebug() << "Number of rows in the result set:" << rowCount;

        ui->equipment_list->setModel(model);
        ui->equipment_list->resizeColumnsToContents(); // 调整列宽度使数据能够完全显示






/*
        QStandardItemModel *tableModel = new QStandardItemModel(this);
       ui->equipment_list->setModel(tableModel); // recommend to set model before detail settings

       // set columns
       QStringList columnTitles;
       columnTitles << "id" << "name" << "status" << "action";
       tableModel->setHorizontalHeaderLabels(columnTitles);

   // add contents
   for(int i = 0; i < 7; i++)
   {

       // add button to the last column
       QPushButton *button = new QPushButton("Start");

       // set custom property这三行为按钮设置属性
       button->setProperty("id", i); // set custom property设置按钮id为i
       button->setProperty("name", QString("hello qt tablview %1").arg(i));
       button->setProperty("status", "normal");

       // set click event
       connect(button, &QPushButton::clicked, this, &manager::onTableBtnClicked); // 使用新的连接语法

       // notice every time insert the button at the last line
      ui->equipment_list->setIndexWidget(tableModel->index(tableModel->rowCount() - 1, 3), button);
       ui->equipment_list->resizeColumnsToContents(); // 调整列宽度使数据能够完全显示
   }




   */

}





manager::~manager()
{
    delete ui;
    // 不需要手动删除tableModel，因为它是this的子对象
}




//------------------------auto_button

void manager::onTableBtnClicked()
{
    QPushButton *button = (QPushButton *)sender();
    qDebug() << button->property("id").toInt() << endl;
    qDebug() << button->property("name").toString() << endl;
    qDebug() << button->property("status").toString() << endl;
}



















